package com.base.test.mutual.utils;

import com.alibaba.fastjson.JSON;
import com.base.commons.tools.enums.LanguageEnum;
import com.base.commons.tools.exception.BaseOfException;
import com.base.commons.tools.utils.CameTools;
import com.base.commons.tools.utils.HttpConnectUtil;
import com.base.commons.tools.utils.MD5;
import com.base.test.mutual.exception.ModuleErrorCode;
import com.base.test.mutual.dto.CustomerJwtToken;
import com.base.test.mutual.dto.WmsReqData;
import com.base.test.mutual.properties.WmsProperties;
import com.base.test.mutual.redis.TokenRedis;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author carl
 * @since 2020/1/19
 */
@Log4j2
@Configuration
@EnableConfigurationProperties(WmsProperties.class)
public class WMSHttpUtils {

    @Autowired
    private WmsProperties wmsProperties;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private CustomerHttpUtils customerHttpUtils;

    @Autowired
    private TokenRedis tokenRedis;


    /**
     * wms 远程接口
     *
     * @param requestObj 请求参数
     * @param url        接口路径
     * @param method     方法
     * @param clazz      响应结果的类型
     * @param <T>        响应结果的类型
     * @return
     */
    public <T> T execute(T requestObj, String url, String method, Class<?> clazz) {

        Object obj = null;
        String req = null;
        String sign = null;
        String request = null;
        ResponseEntity res = null;
        WmsReqData requestParam = new WmsReqData();
        try {
            requestParam.setRequestId(UUID.randomUUID().toString());
            requestParam.setRequestTime(String.valueOf(System.currentTimeMillis()));

            //String language = httpServletRequest.getHeader(HttpHeaders.ACCEPT_LANGUAGE);
            requestParam.setLanguage(LanguageEnum.convertToNonstandard("zh_CN"));
            if (null != requestObj) {
                //入参转化下划线
                request = CameTools.toUnderlineJSONString(requestObj);
                requestParam.setRequestData(JSON.parseObject(request));
            } else {
                List<String> dataList = Collections.EMPTY_LIST;
                requestParam.setRequestData(dataList);
            }
            sign = MD5.MD5Encode(requestParam.getRequestTime() + wmsProperties.getEncryKey());
            requestParam.setSign(sign);
            requestParam.setAppCode(wmsProperties.getAppCode());

            //入参转化下划线
            req = CameTools.toUnderlineJSONString(requestParam);

            //url="http://192.168.98.112:9696"+url;
            url = wmsProperties.getUrl() + url;
            log.info("模块Module:{},url:{},请求参数[{}]", "WMS", url, req);
            res = HttpConnectUtil.tempHttp(req, url, null, method, new HashMap<>(), String.class);
            obj = res.getBody();
            //obj = CameTools.convert(JSON.toJSON(res.getBody()).toString());
            log.info("模块Module:{},url:{},请求结果：{}", "WMS", url, obj);
        } catch (Exception e) {
            log.error("模块Module:{},url:{},请求参数[{}],异常信息：{}", "WMS", url, req, e);
            throw new BaseOfException(ModuleErrorCode.WMS_FAILED, e, "!");
        }
        return (T) obj;
    }

    public <T> T executeSystemToken(T requestObj, String url, String method, Class<?> clazz) {
        url = wmsProperties.getGatewayurl() + url;
        HttpHeaders headers = new HttpHeaders();
        CustomerJwtToken jwtToken = getJwtToken();
        if (jwtToken != null) {
            headers.add(HttpHeaders.AUTHORIZATION, jwtToken.getToken());
        }
        headers.add(HttpHeaders.ACCEPT_LANGUAGE, "zh-cn");
        log.info("模块Module:{},url:{},请求参数{}", "WMS", url, JSON.toJSONString(requestObj));
        ResponseEntity res = HttpConnectUtil.tempHttp(requestObj, url, headers, method, new HashMap<>(), clazz);
        log.info("模块Module:{},url:{},请求结果：{}", "WMS", url, res.getBody());
        return (T) res.getBody();
    }

    /**
     * 获取 wms token
     *
     * @return
     */
    public CustomerJwtToken getJwtToken() {
        String redisKey = RedisKeys.getWmsTokenKey(wmsProperties.getAppId() + wmsProperties.getAppKey());
        CustomerJwtToken token = (CustomerJwtToken) tokenRedis.get(redisKey);
        if (token == null || isTokenExpired(token.getExpiration())) {
            token = customerHttpUtils.generateSystemToken(wmsProperties.getAppId(), wmsProperties.getAppKey());
            tokenRedis.set(token, redisKey);
        }
        return token;
    }

    /**
     * 刷新 wms token
     *
     * @return
     */
    public void refreshJwtToken() {
        String redisKey = RedisKeys.getWmsTokenKey(wmsProperties.getAppId() + wmsProperties.getAppKey());
        CustomerJwtToken token = customerHttpUtils.generateSystemToken(wmsProperties.getAppId(), wmsProperties.getAppKey());
        tokenRedis.set(token, redisKey);
    }

    /**
     * token是否过期
     *
     * @return true：过期
     */
    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }


}
